package com.senseu.testserver.repository;

import com.senseu.testserver.model.Device;
import jakarta.persistence.LockModeType;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface DeviceRepository extends JpaRepository<Device, Long> {

    List<Device> findDeviceByNode(String node);

    @Modifying
    @Transactional
    @Query("UPDATE Device d SET d.status = :status WHERE d.node = :node")
    int updateStatusByNode(@Param("node") String node, @Param("status") int status);

    List<Device> findDevicesByStatus(int status);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT d FROM Device d WHERE d.status = 0 and d.udid like '%:%'")
    List<Device> findIdleDevicesForUpdate(Pageable pageable);

    List<Device> findDevicesByUdid(String udid);
}
